package cn.edu.jou.service.impl;

import cn.edu.jou.common.CustomException;
import cn.edu.jou.entity.Category;
import cn.edu.jou.entity.Dish;
import cn.edu.jou.entity.Setmeal;
import cn.edu.jou.mapper.CategoryMapper;
import cn.edu.jou.service.CategoryService;
import cn.edu.jou.service.DishService;
import cn.edu.jou.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long ids) {
        //log.info(category.toString());
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件，根据分类id进行查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, ids);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        //查询当前分类是否关联了菜品，如果已关联，抛出一个业务异常
        if (count1 > 0) {
            //抛出一个运行时异常
            throw new CustomException("关联一个或一个以上菜品，无法删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件，根据分类id查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, ids);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2 > 0) {
            //如果已关联一个以上菜品，则抛出一个运行时异常
            throw new CustomException("关联一个或一个以上套餐，无法删除");
        }
        super.removeById(ids);
    }
}
